import 'package:flutter/material.dart';

class FormExample extends StatefulWidget {
  @override
  _FormExampleState createState() => _FormExampleState();
}

class _FormExampleState extends State<FormExample> {
  @override
  Widget build(BuildContext context) {
    GlobalKey _formKey = new GlobalKey<FormState>();

    FocusNode focusNodeName = FocusNode();
    FocusNode focusNodePassword = FocusNode();

    return Scaffold(
      appBar: AppBar(
        title: Text("FormExample"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(10.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              TextFormField(
                onEditingComplete: () {
                  focusNodePassword.requestFocus();
                },
                focusNode: focusNodeName,
                decoration: InputDecoration(
                  labelText: "用户名：",
                  icon: Icon(Icons.person),
                ),
                validator: (String value) {
                  return value.trim().length > 0 ? null : "用户名不能为空";
                },
              ),
              TextFormField(
                obscureText: true,
                focusNode: focusNodePassword,
                decoration: InputDecoration(
                  labelText: "密码：",
                  icon: Icon(Icons.lock),
                ),
                validator: (String value) {
                  return value.trim().length > 6 ? null : "密码不能少于6位";
                },
              ),
              Padding(
                padding: const EdgeInsets.only(top: 30.0),
                child: Row(
                  children: [
                    Expanded(
                      child: RaisedButton(
                        padding: EdgeInsets.all(15.0),
                        onPressed: () {
                          // 失去焦点，收起键盘。
                          focusNodeName.unfocus();
                          focusNodePassword.unfocus();

                          if ((_formKey.currentState as FormState).validate()) {
                            print("校验通过！");
                          }
                        },
                        child: Text("登录"),
                        textColor: Colors.white,
                        color: Theme.of(context).primaryColor,
                      ),
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
